import { sql, normalizePaginationParams } from "#/utils";
import type { TaskLog } from "#/types";

export default {
  queryList(pageInfo): Promise<TaskLog[]> {
    const { page, pageSize, searchContent } =
      normalizePaginationParams(pageInfo);
    if (searchContent) {
      return sql` 
  SELECT * FROM  t_task_logs 
  WHERE task_name LIKE CONCAT('%', ${searchContent}, '%')
    ORDER BY create_time  
  DESC LIMIT ${pageSize} OFFSET ${(page - 1) * pageSize}`;
    }
    return sql` 
  SELECT * FROM  t_task_logs 
    ORDER BY create_time  
  DESC LIMIT ${pageSize} OFFSET ${(page - 1) * pageSize}`;
  },
  queryTotal(label = "", value = ""): Promise<TaskLog[]> {
    if (value) {
      return sql`SELECT * FROM  t_task_logs 
  WHERE task_name LIKE CONCAT('%', ${value}, '%')`;
    }
    return sql`SELECT * FROM t_task_logs`;
  },

  insert(data: TaskLog) {
    return sql`
 INSERT INTO t_task_logs 
  (id, task_id, task_name , create_time,status,error_message,result)  
    VALUES  
  ( ${data.id},${data.task_id},${data.task_name},${data.create_time},${data.status},${data.error_message},${data.result})`;
  },

  update(data: TaskLog) {
    return sql`
    UPDATE t_task_logs
      SET create_time=${data.create_time},status=${data.status},error_message=${data.error_message},result=${data.result}
    WHERE id = ${data.id}`;
  },

  queryCount(): Promise<
    {
      total_calls: number;
      success_calls: number;
      failed_calls: number;
    }[]
  > {
    return sql` 
  SELECT 
    COUNT(CASE WHEN status IN (0, 1) THEN 1 END) AS total_calls,
    SUM(CASE WHEN status = 1 THEN 1 ELSE 0 END) AS success_calls,
    SUM(CASE WHEN status = 0 THEN 1 ELSE 0 END) AS failed_calls
FROM t_task_logs;`;
  },
};
